#include "gd32f30x.h"
#include "systick.h"
#include "usart.h"
#include "led.h"
#include "timer.h"
#include "app_nbiot.h"
#include "soft_i2c.h"
#include "sht3x.h"

extern uint8_t update_flag;
extern int udp_socket;

int main(void)
{
//	uint32_t sn;
	char res_buf[128];
	char data_buf[128];
	int times = 0;
	double Tem_val,Hum_val;
	systick_config();	/* 配置系统时钟 */
	LED_init();			/* 初始化 LED */	
	uart_init(115200);	/* 初始化USART0 */
	uart1_init(9600);	/* 初始化USART1 */
	timer5_init(50000,12000);	/* 定时5000ms*/
	
	printf("Hello world! \r\n");
	
	while(NB_Start())
	{
		u1_printf("AT+NRB\r\n");	/* 重启*/
		while(USART1_RX_NUM == 0) 
			;
		if(USART1_RX_NUM >0)
		{
			printf("NBIoT: %s\r\n",rx1_date_buf);
			USART1_RX_NUM = 0;
		}
	}
	printf("start OK\r\n");
	
//	IIC_Init();
//	if( 0 == SHT3x_ReadSerialNumber(&sn))
//		printf("ReadSerialNumber OK sn = 0x%x \r\n",sn);
//	else
//		printf("ReadSerialNumber ERR \r\n");
	
	if( 0 == SHT3x_Init())
		printf("SHT3x_Init OK \r\n");
	else
		printf("SHT3x_Init ERR \r\n");
	
	while(1)
	{	
		if(update_flag  == 1)
		{
			update_flag = 0;
			times++;
			LED(times%2);
			/* 采集温湿度数据然后上传到EMQ */
			if(SHT3x_Get_Humiture_periodic(&Tem_val,&Hum_val) == 0)
			{
				sprintf(data_buf,"{\"temperature\":%6.2lf ,\"humidity\":%6.2lf }",Tem_val,Hum_val);
				NB_Send_data("39.96.35.207", "SHT3x", data_buf);
				printf("%s\r\nData send to EMQ...\r\n",data_buf);
			}
			else
				printf("Get_Humiture ERR\r\n");
		}
		if(USART1_RX_NUM >0)
		{
			USART1_RX_NUM = 0;
			if(Find_string((char *)rx1_date_buf,"+NSONMI:","\r\n",res_buf)>0)
			{
				u1_printf("AT+NSORF=%d,%d\r\n",udp_socket,res_buf[2]-'0');
			}
			printf("NBIOT: %s\r\n",rx1_date_buf);			
		}
		if(USART_RX_NUM >0)
		{
			USART_RX_NUM = 0;
			u1_printf("%s",rx0_date_buf);			
		}
	}
}

